package com.fzt.framework.config;


import com.fzt.framework.filter.AuthenticationTokenFilter;
import com.fzt.framework.properties.AuthIgnoreUrls;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;


/**
 * <p>
 *
 * </p>
 *
 * @author 非洲铜
 * @since 2022-12-07
 */
@AllArgsConstructor
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final AuthIgnoreUrls            authIgnoreUrls;
    private final AuthenticationTokenFilter authenticationTokenFilter;

    @Bean
    public PasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        List<String> authIgnoreUrls = this.authIgnoreUrls.getAuthIgnoreUrls();
        String[]     ignoreUrls     = authIgnoreUrls.toArray(new String[0]);

        httpSecurity
                .csrf().disable()
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                .antMatchers(ignoreUrls).permitAll()
                .anyRequest().authenticated();
    }
}
